﻿'use strict';
var express = require('express');
var router = express.Router();
var basicAuth = require('express-basic-auth');
var path = require('path')
var fs = require('fs')
var MongoClient = require('mongodb').MongoClient;

var server_status = require("../websocket.js")
var server_list = require("../server.json")

var config = require('../config.json')
var pass = config["pass"];
var db_url = config["mongo"]

//admin need to manual config
router.use(basicAuth({
    users: {
        "admin": pass
    },
    challenge: true
}))

/* GET home page. */
router.get('/', function (req, res) {
    res.render('admin', {});
});

console.log(path.resolve(__dirname, '../server.json'))

router.post('/add', function (req, res) {
    server_list[req.body.token] = {
        "name": req.body.name
    }

    fs.writeFile(path.resolve(__dirname, '../server.json'), JSON.stringify(server_list), function (err) {
        if (err) {
            throw err;
        }
    });
    server_status[req.body.token] = {
        "name": req.body.name
    }
    MongoClient.connect(db_url).then(
        async (db) => {
            let dbo = db.db("serverstatus");
            let _status = await dbo.createCollection(req.body.name);
            let server_collection = dbo.collection(req.body.name);
            let _res = await server_collection.createIndex({
                "createdAt": 1
            }, {
                expireAfterSeconds: 1800
            })
        }
    );
    res.json(server_list)

});

module.exports = router;